package tools

import (
	"bytes"
	"crypto/md5"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"math/big"
	"net/http"
	"strconv"
	"time"
)

func GenerateAPIKey(userID string, registrationTime time.Time) string {
	// 将用户ID和注册时间转换为字符串
	data := userID + registrationTime.String()

	// 使用SHA256哈希函数生成API密钥
	hash := sha256.Sum256([]byte(data))
	APIKey := fmt.Sprintf("%x", hash)

	return APIKey
}

func EtherStrToWeiBigInt(etherStr string, decimals uint) (*big.Int, bool) {
	etherAmount := new(big.Float)
	_, ok := etherAmount.SetString(etherStr)
	if !ok {
		return nil, false
	}

	// 计算代币单位，即1 Ether等于10的decimals次方Wei
	tokenUnit := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimals)), nil))

	// 将Ether数量乘以单位得到Wei
	wei := new(big.Int)
	etherAmount.Mul(etherAmount, tokenUnit).Int(wei)

	return wei, true
}

// EtherBigIntToWeiStr 将Ether的*big.Float转换为Wei的字符串形式
func EtherBigIntToWeiStr(ether *big.Float, decimals uint) string {
	tokenUnit := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimals)), nil))
	wei := new(big.Int)
	ether.Mul(ether, tokenUnit).Int(wei)
	return wei.String()
}

func WeiStrToEtherBigInt(weiStr string, decimals uint) (*big.Float, bool) {
	wei := new(big.Int)
	_, ok := wei.SetString(weiStr, 10)
	if !ok {
		return nil, false
	}

	ether := new(big.Float).SetInt(wei)
	tokenUnit := new(big.Float).SetInt(new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(decimals)), nil))
	ether.Quo(ether, tokenUnit).SetPrec(4)

	return ether, true
}

// VerifySign 验证签名
func VerifySign(body string, key string, nonce string, timestamp string, sign string) bool {
	data := []byte(body + key + nonce + timestamp)
	hash := md5.Sum(data)
	md5String := hex.EncodeToString(hash[:])
	fmt.Println(md5String, 1111)
	//fmt.Println(sign, 222)
	if md5String != sign {
		return false
	}
	return true
}

// 参数month以月为单位 加上当前时间
func AddTimestamp(maturityTime int64, month int, typeVal string) int64 {
	var timestamp int64
	now := time.Now()
	if maturityTime != 0 {
		now = time.Unix(maturityTime, 0)
	}

	var addDate time.Time

	switch typeVal {
	case "1":
		addDate = now.AddDate(month, 0, 0)
	case "2":
		addDate = now.AddDate(0, month, 0)
	case "3":
		addDate = now.AddDate(0, 0, month)
	case "4":
		addDate = now.Add(time.Duration(month) * time.Hour)
	default:
		log.Println("获取产品类型失败")
	}
	//addDate := now.AddDate(0, month, 0)
	//addDate := now.AddDate(0, 0, 2)

	addDate = time.Date(addDate.Year(), addDate.Month(), addDate.Day(), 23, 59, 59, 0, time.Local)
	timestamp = addDate.Unix()
	return timestamp
}

func SendGet(url string) ([]byte, error) {
	// 将data转换为json字节数组
	jsonData, err := json.Marshal(nil)
	if err != nil {
		log.Println("jsonData error:", err)
		return nil, err
	}

	// 创建http请求
	req, err := http.NewRequest("GET", url, bytes.NewBuffer(jsonData))
	if err != nil {
		log.Println("NewRequest error:", err)
		return nil, err
	}

	// 发送请求
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Println("Do error:", err)
		return nil, err
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println("body error:", err)
		return nil, err
	}

	return body, nil
}

// 除法
func Mul(num1 string, num2 string) string {

	// 将字符串转换为大数
	numerator := new(big.Float)
	denominator := new(big.Float)

	numerator.SetString(num1)
	denominator.SetString(num2)

	// 计算相除并乘以100
	result := new(big.Float).Quo(numerator, denominator)
	result.Mul(result, big.NewFloat(100))

	// 保留4位小数
	result = new(big.Float).SetPrec(128).Set(result).SetMode(big.ToNearestEven)
	result = result.SetPrec(4)

	return result.String()

}

func Muliplication(num1 string, num2 string) string {

	// 创建浮点数
	numerator := new(big.Float)
	denominator := new(big.Float)

	// 设置值
	numerator.SetString(num1)   // 分子
	denominator.SetString(num2) // 分母

	// 进行惩罚（除法）
	result := new(big.Float).Mul(numerator, denominator)

	// 打印结果
	fmt.Printf("Result of punishment (division): %s\n", result.String())

	return result.String()
}

// 两个字符串类型转float64 在做除法
func Div(num1 string, num2 string, prec int) string {
	// 将字符串转换为浮点数
	numerator, _ := strconv.ParseFloat(num1, 64)
	denominator, _ := strconv.ParseFloat(num2, 64)

	// 进行除法运算
	result := numerator / denominator

	//float64转string
	return strconv.FormatFloat(result, 'f', prec, 64)

}
